'''
Created on Jan 20, 2011

@author: gisadmin
'''
import re
SHOW_TABLES_ID_COLUMN = "table id"
SHOW_TABLES_NAME_COLUMN = "name"

def parseShowTablesResults(content):
    lines = content.splitlines()
    lines = [item for item in lines if item]
    if not lines: return None
    
    colHeaders = [col.strip() for col in lines[0].split(',')]
    id_col_index = colHeaders.index(SHOW_TABLES_ID_COLUMN)
    name_col_index = colHeaders.index(SHOW_TABLES_NAME_COLUMN)
    
    colValues = [col.split(',') for col in lines[1:]]
    
    result = dict()
    for cols in colValues:
        result[cols[name_col_index]] = cols[id_col_index]
    return result

def parseSelectResults(content):
    lines = content.splitlines()
    lines = [item for item in lines if item]
    if not lines: return None
    
    colHeaders = [col.strip() for col in lines[0].split(',')]
    colValues = [col.split(',') for col in lines[1:]]
    result = list()
    for col in colValues:
        row = dict()
        for id, name in enumerate(colHeaders):
            row[name] = col[id]
        result.append(row)
    return result

def removeQuotesAroundStrings(value):
    if value and (value[0] == value[-1:]):
        if value[0] in ["'", '"']: return value[1:-1]
    return value

def removeQuotesAroundStringsInList(values):
    return [removeQuotesAroundStrings(value) for value in values]
            

def parseSelectResultsWithShape(content):
    lines = content.splitlines()
    lines = [item for item in lines if item]
    if not lines: return None
    
    colHeaders = [col.strip() for col in lines[0].split(',')]
    PATTERN = re.compile(r'''((?:[^,"']|"[^"]*"|'[^']*')+)''')
    colValues = [PATTERN.split(col)[1::2] for col in lines[1:]]
    result = list()
    for col in colValues:
        fieldValues = removeQuotesAroundStringsInList(col)
        row = dict()
        for id, name in enumerate(colHeaders):
            row[name] = fieldValues[id]
        result.append(row)
    return result

def parseInsertResults(content):
    lines = content.splitlines()
    lines = [item for item in lines if item]
    if not lines: return None
    
    colHeader = lines[0]
    return [(colHeader, entry) for entry in lines[1:]]

def parseInsertResult(content):
    lines = content.splitlines()
    lines = [item for item in lines if item]
    if not lines: return None
    
    return lines[0].strip(), lines[1].strip()
    